import { searchProducts } from '../../../services/product/searchProducts';
import Toast from 'tdesign-miniprogram/toast/index';

Page({
  data: {
    goodsList: [],
    hasLoaded: false,
    keywords: '',
    loadMoreStatus: 0,
    loading: true,
  },

  onLoad(options) {
    const { searchValue = '' } = options || {};
    this.setData({
      keywords: decodeURIComponent(searchValue),
    });
    if (searchValue) {
      this.init();
    }
  },

  async init() {
    const { keywords } = this.data;
    if (!keywords || !keywords.trim()) {
      this.setData({
        hasLoaded: true,
        loading: false,
        goodsList: [],
        loadMoreStatus: 0,
      });
      return;
    }

    this.setData({
      loadMoreStatus: 1,
      loading: true,
    });

    try {
      const goodsList = await searchProducts(keywords);
      this.setData({
        goodsList: goodsList,
        loadMoreStatus: 0,
        hasLoaded: true,
        loading: false,
      });
    } catch (error) {
      console.error('搜索失败:', error);
      this.setData({
        goodsList: [],
        loadMoreStatus: 0,
        hasLoaded: true,
        loading: false,
      });
      wx.showToast({
        title: '搜索失败，请稍候重试',
        icon: 'none',
      });
    }
  },

  handleSubmit(e) {
    const { value } = e.detail;
    if (value && value.trim()) {
      this.setData({
        keywords: value.trim(),
        hasLoaded: false,
        loading: true,
        goodsList: [],
      });
      this.init();
    }
  },

  gotoGoodsDetail(e) {
    const { index } = e.detail;
    const { spuId } = this.data.goodsList[index];
    console.log('搜索结果页商品点击，商品ID:', spuId);
    wx.navigateTo({
      url: `/pages/goods/details/index?productId=${spuId}`,
    });
  },

  handleAddCart() {
    Toast({
      context: this,
      selector: '#t-toast',
      message: '点击加入购物车',
    });
  },
});